package com.cn.cash.baselib;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.cn.cash.baselib.permission.RequestPermissionHelper;
import com.cn.cash.baselib.retrofit.RetrofitManager;
import com.cn.cash.baselib.retrofit.RetrofitResponseListener;
import com.cn.cash.baselib.view.AlertWidget;

import java.io.Serializable;
import java.lang.reflect.Field;

import io.reactivex.Observable;


/**
 * AppCompatActivity基类
 * Created by CN on 2016/10/31.
 */
public abstract class CNBaseActivity extends AppCompatActivity {
    private Toolbar toolBar;
    private ImageButton imgLeft;
    private ImageButton imgRight;
    private TextView txtTitle;
    private TextView txtTitleRight;
    private TextView txtTitleLeft;
    private FrameLayout fltContent;
    public View viewChildContent;
    private View includeToolbar;
    private AlertWidget bar;
    private View viewNetError;
    private View viewEmpty;
    private View viewLogin;
    private View rltBase;
    private View titleCutLine;
    private boolean isPrepared = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CNApp.getInstance().addActivity(this);
        setContentView(R.layout.activity_base);
        bindViews();
        if(isShowTitleInit()){
            toolBar.setVisibility(View.VISIBLE);
        }else{
            toolBar.setVisibility(View.GONE);
        }
        fltContent.postDelayed(new Runnable() {
            @Override
            public void run() {
                addChildContentView(onGetChildView());
            }
        },getDelayTimeOnLoadChildView());
    }

    private void bindViews() {
        includeToolbar = findViewById(R.id.includeToolbar);
        toolBar = (Toolbar) includeToolbar.findViewById(R.id.toolBar);
        titleCutLine = includeToolbar.findViewById(R.id.titleCutLine);
        imgLeft = (ImageButton) includeToolbar.findViewById(R.id.imgLeft);
        imgRight = (ImageButton) includeToolbar.findViewById(R.id.imgRight);
        txtTitle = (TextView) includeToolbar.findViewById(R.id.txtTitle);
        txtTitleRight = (TextView) includeToolbar.findViewById(R.id.txtTitleRight);
        txtTitleLeft = (TextView) includeToolbar.findViewById(R.id.txtTitleLeft);
        fltContent = (FrameLayout) findViewById(R.id.fltContent);
        rltBase = findViewById(R.id.rltBase);
        viewNetError = findViewById(R.id.viewNetError);
        viewNetError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowError(false);
                onReloadData(false);
            }
        });
        viewEmpty = findViewById(R.id.viewEmpty);
        viewLogin = findViewById(R.id.viewLogin);
        viewLogin.findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoginBtnClick();
            }
        });
    }

    /**
     * 添加子contentView
     *
     * @param resId
     */
    private void addChildContentView(int resId) {
        if (resId == 0)
            return;
        viewChildContent = LayoutInflater.from(this).inflate(resId, null);
        fltContent.addView(viewChildContent);
        onBindChildViews();
        onBindChildListeners();
        fltContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (fltContent.getWidth() > 0) {
                    fltContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    onChildViewCreated();
                    isPrepared = true;
                }
            }
        });
    }

    /**
     * 获取子view的layout
     *
     * @return
     */
    protected abstract int onGetChildView();

    /**
     * 初始化绑定view控件
     */
    protected abstract void onBindChildViews();

    /**
     * 初始化绑定监听事件
     */
    protected abstract void onBindChildListeners();

    /**
     * 子view创建
     */
    protected abstract void onChildViewCreated();

    /**
     * ******************
     * 点击error界面重新加载数据
     * ******************
     */
    protected abstract void onReloadData(boolean isRefresh);

    /**
     * ******************
     * 点击登录按钮
     * ******************
     */
    protected void onLoginBtnClick(){}
    /**
     * 子view的延迟加载时间
     * @return
     */
    protected long getDelayTimeOnLoadChildView(){
        return 0;
    }
    /**
     * 设置标题
     *
     * @param resId
     */
    public void setTitleTxt(int resId) {
        setTitleTxt(getString(resId));
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitleTxt(String title) {
        txtTitle.setText(title);
    }

    /**
     * 设置标题字体颜色
     *
     * @param colors
     */
    public void setTitleTxtColor(int colors) {
        txtTitle.setTextColor(getResources().getColor(colors));
    }

    /**
     * 设置标题背景颜色
     *
     * @param colors
     */
    public void setToolBarColor(int colors) {
        toolBar.setBackgroundColor(colors);
    }

    public TextView getMyTitle() {
        return this.txtTitle;
    }

    public void isShowTitle(final boolean isShow) {
        includeToolbar.post(new Runnable() {
            @Override
            public void run() {
                if (isShow) {
                    includeToolbar.setVisibility(View.VISIBLE);
                } else {
                    includeToolbar.setVisibility(View.GONE);
                }
            }
        });
    }
    public void isShowTitleCutLine(boolean isShow) {
        titleCutLine.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    public void showBackImgLeft(int backResId) {
        setImgLeftBg(backResId);
        imgLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackBtnPressed();
                finish();
            }
        });
    }
    public void onBackBtnPressed(){}
    /**
     * 获取标题左侧imgBtn
     *
     * @return
     */
    public ImageButton getImgLeft() {
        return this.imgLeft;
    }


    public void isShowImgLeft(boolean isShow) {
        if (isShow) {
            imgLeft.setVisibility(View.VISIBLE);
        } else {
            imgLeft.setVisibility(View.GONE);
        }
    }

    public void setImgLeftBg(int resId) {
        this.imgLeft.setImageResource(resId);
        isShowImgLeft(true);
    }

    /**
     * 获取右侧imgBtn
     *
     * @return
     */
    public ImageButton getImgRight() {
        return this.imgRight;
    }

    public void isShowImgRight(boolean isShow) {
        if (isShow) {
            imgRight.setVisibility(View.VISIBLE);
        } else {
            imgRight.setVisibility(View.GONE);
        }
    }

    public void setTxtTitleRight(int resId) {
        setTxtTitleRight(getString(resId));
    }

    public void setTxtTitleRight(String titleRight) {
        txtTitleRight.setText(titleRight);
        isShowTxtRight(true);
    }

    public TextView getTxtTitleRight() {
        return txtTitleRight;
    }

    public void isShowTxtRight(boolean isShow) {
        if (isShow) {
            txtTitleRight.setVisibility(View.VISIBLE);
        } else {
            txtTitleRight.setVisibility(View.GONE);
        }
    }

    public void setTxtTitleLeft(int resId) {
        setTxtTitleLeft(getString(resId));
    }

    public void setTxtTitleLeft(String titleLeft) {
        txtTitleLeft.setText(titleLeft);
        isShowTxtLeft(true);
    }

    public TextView getTxtTitleLeft() {
        return txtTitleLeft;
    }

    public void isShowTxtLeft(boolean isShow) {
        if (isShow) {
            txtTitleLeft.setVisibility(View.VISIBLE);
        } else {
            txtTitleLeft.setVisibility(View.GONE);
        }
    }

    public void setImgRightBg(int resId) {
        this.imgRight.setImageResource(resId);
        isShowImgRight(true);
    }

    public View getBaseView() {
        return this.rltBase;
    }

    /**
     * 获取toolBar
     *
     * @return
     */
    public Toolbar getToolBar() {
        return this.toolBar;
    }

    /**
     * 获取状态栏的高度
     *
     * @return
     */
    public int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 状态栏透明
     */
    public void setStatusBarTrans() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    public void setStatusBarColor(int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                getWindow().setStatusBarColor(getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T extends Serializable>T getSerializableExtra(Class<T> serializableClass){
        return (T) getIntent().getSerializableExtra(getRequestTag());
    }
    public String getStringExtra(){
        return getIntent().getStringExtra(getRequestTag());
    }
    public void start(Serializable data, Activity from, Class to){
        Intent intent = new Intent(from,to);
        intent.putExtra(to.getSimpleName(),data);
        from.startActivity(intent);
    }
    public void start(String data, Activity from, Class to){
        Intent intent = new Intent(from,to);
        intent.putExtra(to.getSimpleName(),data);
        from.startActivity(intent);
    }
    public void start(Serializable data, Class to){
        Intent intent = new Intent(this,to);
        intent.putExtra(to.getSimpleName(),data);
        startActivity(intent);
    }
    public void startActivity(Serializable data, Class to){
        Intent intent = new Intent(this,to);
        intent.putExtra(to.getSimpleName(),data);
        startActivity(intent);
    }
    public void start(String data, Class to){
        Intent intent = new Intent(this,to);
        intent.putExtra(to.getSimpleName(),data);
        startActivity(intent);
    }
    public CNBaseActivity getActivity(){
        return this;
    }
    /**
     * 启动activity
     *
     * @param tClass
     * @param isClose 是否关闭本界面
     */
    public void startActivity(Class<?> tClass, Bundle extras, boolean isClose) {
        Intent intent = new Intent(this, tClass);
        if (extras != null)
            intent.putExtras(extras);
        startActivity(intent);
        if (isClose)
            this.finish();
    }
    /**
     * 启动activity
     *
     * @param tClass
     */
    public void startActivity(Class<?> tClass) {
        startActivity(tClass,null,false);
    }
    /**
     * 启动activity
     *
     * @param tClass
     * @param isClose 是否关闭本界面
     */
    public void startActivity(Class<?> tClass,boolean isClose) {
        startActivity(tClass,null,isClose);
    }

    /**
     * 获取网络请求的tag
     *
     * @return
     */
    public String getRequestTag() {
        return this.getClass().getSimpleName();
    }

    /**
     * 通过tag撤销请求
     */
    public void cancelByTag(String tag) {
        if (tag == null)
            return;
        RetrofitManager.getInstance().cancelDisposable(tag);
    }

    public void isShowContent(boolean isShow) {
        if (bar != null)
            bar.close();
        if (isShow) {
            fltContent.setVisibility(View.VISIBLE);
            isShowError(false);
            isShowEmpty(false);
            isShowLogin(false);
        } else {
            fltContent.setVisibility(View.GONE);
        }
    }

    public void isShowError(boolean isShow) {
        if (bar != null)
            bar.close();
        if (isShow) {
            viewNetError.setVisibility(View.VISIBLE);
            isShowContent(false);
            isShowEmpty(false);
            isShowLogin(false);
        } else {
            viewNetError.setVisibility(View.GONE);
        }
    }

    public void isShowEmpty(boolean isShow) {
        if (bar != null)
            bar.close();
        if (isShow) {
            viewEmpty.setVisibility(View.VISIBLE);
            isShowContent(false);
            isShowError(false);
            isShowLogin(false);
        } else {
            viewEmpty.setVisibility(View.GONE);
        }
    }

    public void isShowLogin(boolean isShow) {
        if (bar != null)
            bar.close();
        if (isShow) {
            viewLogin.setVisibility(View.VISIBLE);
            isShowContent(false);
            isShowError(false);
            isShowEmpty(false);
        } else {
            viewLogin.setVisibility(View.GONE);
        }
    }
    public void setEmptyImg(int resId){
        ((ImageView)viewEmpty.findViewById(R.id.imgEmpty)).setImageResource(resId);
    }
    public void setEmptyTxt(int resId){
        ((TextView)viewEmpty.findViewById(R.id.txtEmpty)).setText(resId);
    }
    public void showBar() {
        if (bar == null)
            bar = new AlertWidget(this, false);
        bar.setCancelable(false);
        if(!bar.isDialogShow())
            bar.showBar();
    }
    public void showBar(boolean cancelable){
        if (bar == null)
            bar = new AlertWidget(this, false);
        bar.setCancelable(cancelable);
        bar.setCanceledOnTouchOutside(cancelable);
        if(!bar.isDialogShow())
            bar.showBar();
    }
    public void closeBar() {
        if (bar != null) {
            bar.close();
        }
    }

    /**
     * 是否已经加载准备完成
     * @return
     */
    public boolean isPrepared() {
        return isPrepared;
    }
    private RequestPermissionHelper requestPermissionHelper;
    /**
     * 设置权限管理类
     * @param requestPermissionHelper
     */
    public void setRequestPermissionHelper(RequestPermissionHelper requestPermissionHelper){
        this.requestPermissionHelper = requestPermissionHelper;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestPermissionHelper!=null){
            requestPermissionHelper.onActivityResult(requestCode,resultCode,data);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestPermissionHelper != null) {
            requestPermissionHelper.onRequestPermissionsResult(requestCode,permissions,grantResults);
        }
    }
    public void request(Observable observable, RetrofitResponseListener retrofitResponseListener){
        RetrofitManager.getInstance().request(observable,getRequestTag(),retrofitResponseListener);
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelByTag(getRequestTag());
        CNApp.getInstance().removeActivity(this);
    }

    public boolean isShowTitleInit() {
        return true;
    }
}
